package com.yypx.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class EncodingFilter implements Filter {
	private String charset;

	public EncodingFilter() {
		this.charset = "UTF-8";
	}

	public void init(FilterConfig config) throws ServletException {
		String paramCharset = config.getInitParameter("charset");
		if ((paramCharset != null) && (paramCharset.length() > 0))
			this.charset = paramCharset;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		if ((uri.endsWith("html")) || (uri.endsWith("htm")) || (uri.endsWith("xml"))) {
			chain.doFilter(request, response);
			return;
		}
		request.setCharacterEncoding(this.charset);
		response.setCharacterEncoding(this.charset);
		chain.doFilter(request, response);
	}

	public void destroy() {
	}
}
